// app/service/user.js
const BaseService = require('./base')
const { Op } = require('sequelize')
class UserService extends BaseService {
	constructor(...args) {
		super(...args)
		this.modelName = 'User'
	}
	async add(obj) {
		const { username } = obj
		const oldUser = await this.ctx.model.User.findOne({
			where: {
				username,
			},
		})

		if (oldUser)
			return {
				flag: false,
				msg: '用户名已经存在了',
				code: 400,
			}
		let defaultval = {
			avatar:
				'https://tse1-mm.cn.bing.net/th/id/OIP-C.kgO9vKRBreceGgFw-YoZaAAAAA?pid=ImgDet&rs=1',
		}
		// 密码的加密
		const password = await this.ctx.genHash(obj.password || '123456')
		obj.password = password
		// object浅拷贝
		obj = Object.assign(obj, defaultval)
		////////////////////事务
		const data = await this.ctx.model.User.create(obj)
		const createdId = data.dataValues.id
		const roleIds = obj.roleIds || [2]
		for (let i = 0; i < roleIds.length; i++) {
			await this.ctx.model.RoleUser.create({
				userId: createdId,
				roleId: roleIds[i],
			})
		}

		if (data) {
			return {
				flag: true,
				data,
			}
		} else {
			return {
				flag: false,
				msg: '数据添加错误',
				code: 400,
			}
		}
	}
	async login(obj) {
		const { username, password } = obj
		const oldUser = await this.ctx.model.User.findOne({
			where: {
				username,
			},
		})
		if (!oldUser)
			return {
				flag: false,
				msg: '账号错误',
			}
		// 加密密码对比
		const { password: dbPwd } = oldUser.dataValues
		const checked = await this.ctx.compare(password, dbPwd)
		if (checked) {
			// 创建jwt
			// 刪除密碼
			delete oldUser.password
			let token = this.app.jwt.sign(
				{
					oldUser,
				},
				this.app.config.jwt.secret,
				{
					expiresIn: '24h',
				}
			)
			token = 'Bearer ' + token
			// 保存到cookie
			this.ctx.cookies.set('token', token, {
				maxAge: 8640000,
				httpOnly: true,
			})
			// const userInfo = this.ctx.session.userInfo

			return {
				flag: true,
				msg: '登录成功',
				data: {
					token,
					userInfo: oldUser,
				},
			}
		} else {
			return {
				flag: false,
				msg: '密码错误',
			}
		}
	}
	async updateList(arr) {
		let count = 0
		for (let i = 0; i < arr.length; i++) {
			let user = arr[i]
			const u = await this.ctx.model[this.modelName].findOne({
				where: {
					username: {
						[Op.eq]: user.username,
					},
				},
			})
			// 没找到了数据证明不存在相同信息
			if (!u) {
				// 创建用户
				const password = await this.ctx.genHash('123456')

				let res = await this.ctx.model[this.modelName].create({
					password: password,
					...user,
				})
				// 拿到用户创建的id
				const createdId = res.dataValues.id
				// 创建 角色
				await this.ctx.model.RoleUser.create({
					userId: createdId,
					roleId: user.roleId || 2,
				})

				if (res) count++
			} else {
				// 找到了数据证明存在，不能进行添加
				continue
			}
		}
		return {
			flag: true,
			count,
		}
	}
	async del(ids) {
		if (!Array.isArray(ids)) ids = [ids]
		let transaction

		try {
			// 建立事务对象
			transaction = await this.ctx.model.transaction()
			for (let i = 0; i < ids.length; i++) {
				const id = ids[i]
				// 删除用户表
				let res = await this.ctx.model[this.modelName].destroy(
					{
						where: {
							id: {
								[Op.eq]: id,
							},
						},
					},
					{
						transaction,
					}
				)
				// 删除关联表的数据
				let res2 = await this.ctx.model.RoleUser.destroy(
					{
						where: {
							userId: {
								[Op.eq]: id,
							},
						},
					},
					{
						transaction,
					}
				)

				if (!res || !res2) {
					throw Error //数据不存在就回滚
				}
			}
			// 提交事务
			await transaction.commit()
			return {
				flag: true,
			}
		} catch (error) {
			// 事务回滚
			console.log(error)
			await transaction.rollback()
			return {
				flag: false,
				msg: '删除失败',
				code: 400,
			}
		}
	}
	async update(obj) {
		// 建立事物
		let transaction
		try {
			transaction = await this.ctx.model.transaction()
			// 更新用户表的信息

			let res = await this.ctx.model[this.modelName].update(
				{
					...obj,
				},
				{
					where: {
						id: {
							[Op.eq]: obj.id,
						},
					},
				},
				{
					transaction,
				}
			)
			// 跟新角色关联表的信息
			// 先找到有没有
			const findUser = await this.ctx.model.RoleUser.findOne({
				where: {
					userId: {
						[Op.eq]: obj.id,
					},
				},
			})
			// 先全部删除在添加

			if (findUser) {
				let res2 = await this.ctx.model.RoleUser.destroy(
					{
						where: {
							userId: {
								[Op.eq]: obj.id,
							},
						},
					},
					{
						transaction,
					}
				)
				if (!res2) {
					throw Error
				}
			}
			if (obj.roleIds) {
				for (let index = 0; index < obj.roleIds.length; index++) {
					let res3 = await this.ctx.model.RoleUser.create(
						{
							userId: obj.id,
							roleId: obj.roleIds[index],
						},
						{
							transaction,
						}
					)
					if (!res3) {
						throw Error
					}
				}
			}

			// 都成功 提交事务
			if (!res) {
				throw Error
			}
			await transaction.commit()
			return {
				flag: true,
			}
		} catch (error) {
			// 事物回滚
			console.log(error)
			await transaction.rollback()
			return {
				flag: false,
				msg: '修改失败',
				code: 400,
			}
		}
	}
	async updatePwd(obj) {
		return await this.ctx.model[this.modelName].update(
			{
				password: await this.ctx.genHash(obj.password),
			},
			{
				where: {
					id: {
						[Op.eq]: obj.id,
					},
				},
			}
		)
	}
	async getUserInfoById(id) {
		return await this.ctx.model[this.modelName].findOne({
			where: {
				id: {
					[Op.eq]: id,
				},
			},
			attributes: {
				exclude: ['password'],
			},
			distinct: true,
			include: [
				{
					through: {
						attributes: [],
					},
					model: this.ctx.model.Role,
					attributes: ['name', 'remark'],
				},
			],
		})
	}
}

module.exports = UserService
